extends CharacterBody2D


const SPEED = 100.0
const JUMP_VELOCITY = -300.0

var is_on_ladder: bool = false
var fruit_count: int = 0

@onready var animated_sprite_2d: AnimatedSprite2D = $AnimatedSprite2D

func _physics_process(delta: float) -> void:
	var direction := Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
	velocity.x = direction.x * SPEED
	if is_on_floor():
		if direction.x != 0:
			animated_sprite_2d.play("walk")
		else:
			animated_sprite_2d.play("idle")
	else:
		if not is_on_ladder:
			velocity += get_gravity() * delta
	
	if is_on_ladder:
		velocity.y = direction.y * SPEED

	if Input.is_action_just_pressed("ui_accept") and is_on_floor():
		velocity.y = JUMP_VELOCITY
		animated_sprite_2d.play("jump")

	if velocity.x != 0:
		animated_sprite_2d.flip_h = velocity.x < 0

	move_and_slide()

func _on_hit_box_area_entered(area: Area2D) -> void:
	if area.is_in_group("props") and area.name.begins_with("Ladder"):
		is_on_ladder = true
	
	if area.is_in_group("fruits"):
		fruit_count += 1
		area.queue_free()
		print("Fruits collected: %d" % fruit_count)
	
	if fruit_count >= 2:
		print("You win!")

func _on_hit_box_area_exited(area:Area2D) -> void:
	if area.is_in_group("props") and area.name.begins_with("Ladder"):
		is_on_ladder = false


func _on_hit_box_body_entered(body:Node2D) -> void:
	if body.is_in_group("danger"):
		get_tree().reload_current_scene()
		print("You died!")
		return
